package cn.com.member.controller.system;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.service.ApiUploadService;
/*import com.magic.cloud.common.mybatis.BaseController;
import com.magic.cloud.common.oss.OssUtil;
import com.magic.cloud.common.qiniu.MagicUploader;
import com.magic.cloud.filter.MagicPermission;*/
import cn.com.uthink.util.*;
import cn.com.util.ImageUtils;
import cn.com.util.JsonUtil;
import cn.com.util.Utils;

@Controller
public class CommonController {

	@Autowired
	private FileUploadService fileUploadService;
	@Autowired
	private ApiUploadService apiUploadService;

	/**
	 * 上传图片，返回图片的地址
	 * 
	 * @param file
	 *            图片流集合
	 * @param foldername
	 *            图片存放的文件夹名称
	 * @throws Exception
	 */
	@RequestMapping(value = "file/uploadPic")
	public void uploadPic(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "file") MultipartFile[] files) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> urlList = apiUploadService.uploadFileToQiNiu(files);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
			map.put(Utils.DATAS, urlList);
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "上传失败！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 跳转到百度地图界面
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "baiduditu")
	public ModelAndView baiduditu(HttpServletRequest request, HttpServletResponse response, String parent_id)
			throws Exception {
		ModelAndView mv = new ModelAndView("/common/baiduditu");
		return mv;
	}

	@RequestMapping("uploadImage")
	public Response uploadImage(MultipartFile imageFile, HttpServletRequest request, HttpServletResponse response) {
		try {
			String[] string = fileUploadService.upload(request, imageFile, FileUploadService.IMAGE_EXTENSION);
			return ResponseUtil.ok(string[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseUtil.error(ErrorCode.INTERNAL_ERROR);
	}

	@RequestMapping(method = { RequestMethod.DELETE }, value = {
			"/{groupId:g\\d+}/{f1:M\\d+}/{f2:\\w{2}}/{f3:\\w{2}}/{f4:.*}" })
	@ResponseBody
	public void deleteResource(@PathVariable("groupId") String groupId, @PathVariable("f1") String f1,
			@PathVariable("f2") String f2, @PathVariable("f3") String f3, @PathVariable("f4") String f4,
			HttpServletRequest request) {
		String resourcePath = new StringBuilder().append(groupId).append("/").append(f1).append("/").append(f2)
				.append("/").append(f3).append("/").append(f4).toString();
	}

	@RequestMapping("iframeUpload")
	public void uploadFeedBackFile(MultipartFile imageFile, HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream writer = null;
		try {
			writer = response.getOutputStream();
			if (imageFile == null) {
				writer.println("<script>parent.imageCallback('',false)</script>");
			} else {
				String[] string = fileUploadService.upload(request, imageFile, FileUploadService.IMAGE_EXTENSION);
				writer.println(
						"<script>parent.imageCallback('" + URLEncoder.encode(string[0], "UTF-8") + "',true)</script>");
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (writer != null) {
					writer.println("<script>parent.imageCallback('',false)</script>");
				}
			} catch (IOException e1) {
			}
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (Exception e2) {
			}
		}
	}

	@RequestMapping(value = "uploadMuti", method = RequestMethod.POST)
	@ResponseBody
	public Response uploadMuti(MultipartHttpServletRequest iamgefile, String username, Boolean hasError) {
		if (hasError != null) {
			return ResponseUtil.error();
		}
		Map<String, MultipartFile> map = iamgefile.getFileMap();
		for (String filename : map.keySet()) {
			MultipartFile multipartFile = map.get(filename);
			String[] urlString = null;
			if (multipartFile != null) {
				if (multipartFile != null) {
					urlString = fileUploadService.uploadPost(iamgefile, multipartFile);
					System.out.println("urlString[" + urlString + "]");
				}
				if (urlString != null && urlString.length == 2) {
					return ResponseUtil.ok(urlString[1]);
				}
				break;
			}
		}
		return ResponseUtil.error();
	}

	@RequestMapping(value = "uploadMuti2", method = RequestMethod.POST)
	public String uploadMuti(MultipartHttpServletRequest iamgefile, String username, HttpServletRequest request) {
		List<String> list = new ArrayList<String>();
		Map<String, MultipartFile> map = iamgefile.getFileMap();
		for (String filename : map.keySet()) {
			MultipartFile multipartFile = map.get(filename);
			if (multipartFile != null) {
				String[] urlString = null;
				if (multipartFile != null) {
					urlString = fileUploadService.uploadPost(request, multipartFile);
					System.out.println("urlString[" + urlString + "]");
				}
				if (urlString != null && urlString.length == 2) {
					list.add(urlString[1]);
				}
			}
		}
		System.out.println("username[" + username + "]");
		request.setAttribute("images", list);
		return "zzzs/save-image";
	}

	@RequestMapping(value = "postBody")
	@ResponseBody
	public Response postBody(String username, String password, HttpServletRequest request)
			throws JSONException, IOException {
		StringBuffer sReturn = new StringBuffer(512);
		String sTemporary = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
		while ((sTemporary = reader.readLine()) != null) {
			sReturn.append(sTemporary);
		}
		String content = IOUtils.toString(request.getInputStream());
		System.out.println("username[" + username + "]");
		System.out.println("content[" + content + "]");
		System.out.println("magicHeader[" + request.getHeader("magic") + "]");
		return ResponseUtil.ok("");
	}

	@RequestMapping(value = "/app_download/{filename}")
	public void downloadApp(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("filename") String filename) throws IOException {
		String fileSufix = "zhizaozhushou";
		Boolean targetDownload = null;
		System.out.println("filename[" + filename + "]");
		String apkPath = request.getSession().getServletContext().getRealPath("/static") + File.separator + "apk";
		File apkFile = new File(apkPath);
		String[] filenames = apkFile.list();
		if (StringUtils.isNotEmpty(filename) && filenames != null) {
			filename = filename + ".apk";
			for (String apkFilename : filenames) {
				if (apkFilename.equals(filename)) {
					targetDownload = true;
				}
			}
		} else {
			List<Float> vs_ = new ArrayList<Float>();
			for (String string : filenames) {
				String v_ = string.substring(string.indexOf('_') + 1, string.lastIndexOf('.'));
				float _v = Objects.strToFloat(v_, -1);
				if (_v > -1) {
					vs_.add(_v);
				}
			}
			Collections.sort(vs_);
			filename = fileSufix + "_" + vs_.get((vs_.size() - 1)) + ".apk";
			targetDownload = false;
		}
		if (targetDownload != null) {
			File downloadFile = new File(apkPath, filename);
			try {
				response.setContentType("application/vnd.android.package-archive");
				response.setHeader("Content-Length", String.valueOf(downloadFile.length()));
				response.setHeader("content-transfer-encoding", "binary");
				response.setHeader("Content-Disposition", "attachment; filename=" + filename);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(FileUtils.readFileToByteArray(downloadFile));
				outputStream.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/appDownload/{filename}")
	public void appDownload(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("filename") String filename) throws IOException {
		String fileSufix = "zhizaozhushou";
		Boolean targetDownload = null;
		System.out.println("filename[" + filename + "]");
		String apkPath = request.getSession().getServletContext().getRealPath("/static") + File.separator + "weApk";
		File apkFile = new File(apkPath);
		String[] filenames = apkFile.list();
		if (StringUtils.isNotEmpty(filename) && filenames != null) {
			filename = filename + ".apk";
			for (String apkFilename : filenames) {
				if (apkFilename.equals(filename)) {
					targetDownload = true;
				}
			}
		} else {
			List<Float> vs_ = new ArrayList<Float>();
			for (String string : filenames) {
				String v_ = string.substring(string.indexOf('_') + 1, string.lastIndexOf('.'));
				float _v = Objects.strToFloat(v_, -1);
				if (_v > -1) {
					vs_.add(_v);
				}
			}
			Collections.sort(vs_);
			filename = fileSufix + "_" + vs_.get((vs_.size() - 1)) + ".apk";
			targetDownload = false;
		}
		if (targetDownload != null) {
			File downloadFile = new File(apkPath, filename);
			try {
				response.setContentType("application/vnd.android.package-archive");
				response.setHeader("Content-Length", String.valueOf(downloadFile.length()));
				response.setHeader("content-transfer-encoding", "binary");
				response.setHeader("Content-Disposition", "attachment; filename=" + filename);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(FileUtils.readFileToByteArray(downloadFile));
				outputStream.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 上传缩略图
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "pic-upload")
	public void goods_smallpic_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ModelMap model

		String path = ImageUtils.getServletWebAppsPath(request).replace(request.getContextPath(), ImageUtils.IMAGE_ROOT)
				+ "/goods/";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		String fileName = sdfStr + "_" + file.getOriginalFilename();

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String smallpic_path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			file.transferTo(targetFile);
			smallpic_path = ImageUtils.getDataBaseImagePath() + "/goods/" + fileName;

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", smallpic_path);

		} catch (Exception e) {
			e.printStackTrace();
		}
		//
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

}
